<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require_once 'MainPageWidget.php';
class NodeCommunitiesWidget extends MainPageWidget {
	public $title = 'Участвуй в наших сообществах';
	public $from = 'node';
	public $communities = array();
	public $community_list = array();
	public $communitiescount = 5;
	public $widget_view = 'WG_NodeCommunitiesWidget';

	private $communities_count = 5;

	public function Render() {
		$this->communitiescount+=0;
		if ( empty($this->communitiescount) ) {
			$this->communitiescount = $this->communities_count;
		}

		$sql = " select c.oid, max(a.date) as max_date " .
		" from {$this->ctx->store->db->db_prefix}class_community c " .
		" left join {$this->ctx->store->db->db_prefix}class_allfeed a on a.community_oid = c.oid " .
		" left join {$this->ctx->store->db->db_prefix}objects o on c.oid = o.oid " .
		" left join {$this->ctx->store->db->db_prefix}objects o2 on o2.oid = a.oid ";

		if ( !empty($this->community_list) ) {
			foreach ($this->community_list as $oid) {
				$obj = $this->ctx->store->getObject($oid);
				$this->content['communities'][] = array_merge($obj->data, array(
				'ctime' => RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $obj->ctime),
				'oid' => $obj->id
				));
			}
		} else {
			$sql .= ' where (o.is_deleted = 0 or isnull(o.is_deleted)) ' .
			' and (o2.is_deleted = 0 or isnull(o2.is_deleted)) group by c.oid ' .
			' order by max_date desc, c.oid desc ' .
			' limit ' . ($this->communitiescount+0);

			$rec = $this->ctx->store->query($sql);

			while ($item = $rec->next()) {
				$obj = $this->ctx->store->getObject($item['oid']);
				$this->content['communities'][] = array_merge($obj->data, array(
				'ctime' => RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $obj->ctime),
				'oid' => $obj->id
				));
			}
		}

		return $this;
	}

	public function settingsForm() {
		if ( empty($this->community) ) {
			$rs = $this->ctx->store->find("objects where objects.type = :0 and objects.is_deleted=0 order by objects.ctime desc", array("fcommunity"));
			while ($obj = $rs->next()) {
				$this->community[] = array_merge($obj->data, array(
				'oid' => $obj->id
				));
			}
		}

		foreach ( $this->community as $key=>$val ) {
			foreach ( $this->community_list as $oid ) {
				if ( $oid == $val['oid'] ) {
					$this->community[$key]['checked'] = true;
					break;
				}
			}
		}

		if ( !isset($this->params) || !isset($this->params['title']) ) {
			$this->params['title'] = $this->title;
			$this->params['from'] = $this->from;
			$this->params['community'] = $this->community;
		}
	}

	public function setParams( $params ) {
		foreach ( $params as $key=>$val ) {
			if ( isset($this->$key) ) {
				$this->$key = $val;
			}
		}
	}
}